<!-- eslint-disable vue/valid-v-model -->
<template>
    <div class="audit-page">
        <el-form ref="ruleFormRef" :model="selectedData" :inline="true" class="auditFormClass common-search-form">
            <el-form-item prop="premiseName">
                <HouseSearch ref="houseSearch" :project-name="selectedData.premiseName"
                    :audit-status="houseSearchAuditStatus" @onSelect="changeProjectName"></HouseSearch>
            </el-form-item>
            <el-form-item prop="areaArr">
                <el-cascader v-model="selectedData.areaArr" placeholder="请选择区域" :options="commonList.regionList"
                    :props="houseData.optionProps" clearable filterable @change="onChangeArea">
                </el-cascader>
            </el-form-item>
            <el-form-item prop="types">
                <el-select v-model="selectedData.types" multiple placeholder="请选择" collapse-tags clearable class="select"
                    @change="onSearchList">
                    <template #prefix>
                        <div class="label">物业类型
                        </div>
                    </template>
                    <el-option v-for="(item, index) in commonList.permiseList" :key="index" :label="item.name"
                        :value="item.code" />
                </el-select>
            </el-form-item>
            <!-- 2.2.8 隐藏楼盘状态筛选条件 -->
            <!-- <el-form-item prop="status">
                <el-select v-if="+auditStatus === 3" v-model="selectedData.status" placeholder="请选择" class="select"
                    clearable @change="onSearchList">
                    <template #prefix>
                        <div class="label">楼盘状态
                        </div>
                    </template>
                    <el-option v-for="(item, index) in houseData.statusList" :key="index" :label="item.name"
                        :value="item.code" />
                </el-select>
            </el-form-item> -->
            <el-form-item prop="tabooCodes">
                <el-select v-model="selectedData.tabooCodes" multiple collapse-tags clearable placeholder="请选择"
                    class="select" @change="onSearchList">
                    <template #prefix>
                        <div class="label">禁忌行业
                        </div>
                    </template>
                    <el-option v-for="(item, index) in commonList.industryList" :key="index" :label="item.name"
                        :value="item.code" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="resetForm(ruleFormRef)"> 重置
                </el-button>
                <el-button v-if="auditStatus === AuditStatus.PASS" :loading="dialogBtnLoading" @click="onExportPremises">
                    导出
                </el-button>
                <el-button v-if="auditStatus === AuditStatus.PASS" type="primary" @click="onAddDrawerShow">
                    新建楼盘
                </el-button>
                <el-button v-if="auditStatus === AuditStatus.PASS && $btnAuth('importSing')" type="primary"
                    @click="onBatchImport('SING')">
                    批量导入合同信息
                </el-button>
                <el-button v-if="auditStatus === AuditStatus.DRAFT" type="primary" @click="onBatchImport('PREMISES')">
                    批量导入
                </el-button>
            </el-form-item>
        </el-form>
        <xc-table id="xc-table" :data="houseData.houseList" :columns="columns" :loading="houseData.loading">
            <template #provinceName="{ row }"> {{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }} </template>
            <template #onSaleMediaNum="{ row }">
                <el-tooltip v-if="+row.onSaleMediaNum + +row.maintainMediaNum + +row.takeDownMediaNum" placement="right"
                    :content="onMediaNum(row)" raw-content>
                    {{ +row.onSaleMediaNum + +row.maintainMediaNum + +row.takeDownMediaNum }}
                </el-tooltip>
                <span v-else>0</span>
            </template>
            <template #status="{ row }">
                <XcSwitch v-model="row.premiseStatus" class="ml-1" active-text="开启" inactive-text="关闭"
                    :before-change="beforeChange.bind(this, row)" />
            </template>
            <template #taboo="{ row }">
                <span v-if="row.taboo">
                    {{ row.taboo }}
                </span>
                <span v-else>--</span>
            </template>
            <template #action="scope">
                <el-button v-if="+auditStatus === 3" type="text" @click="onCheck(scope, 'VIEW')"> 查看
                </el-button>
                <el-button v-if="+auditStatus === 3" type="text" @click="switchBuildingDrawer(scope)">
                    楼盘图
                </el-button>

                <el-button type="text" @click="onCheck(scope, 'EDIT')">
                    编辑
                </el-button>
                <el-button v-if="auditStatus === AuditStatus.DRAFT" type="text" @click="hanleOnDelete(scope)">
                    删除
                </el-button>
                <el-button v-if="auditStatus === AuditStatus.PASS && $btnAuth('sing')" type="text"
                    @click="hanleOnSign(scope)">
                    合同信息
                </el-button>
            </template>
        </xc-table>
        <Pagination :page-no="selectedData.pageNo" :page-size="selectedData.pageSize" :total="selectedData.total"
            @changePage="changePage" @changePageSize="changePageSize"></Pagination>
        <TipsDailog :title="houseData.title" :content="houseData.content" :dialog-visible="houseData.dialogVisible"
            @onClose="houseData.dialogVisible = false">
            <el-button @click="houseData.dialogVisible = false"> 取消
            </el-button>
            <el-button v-if="+statusPremise === 1" type="primary" @click="updatePremiseStateFun(2, false)">
                确认
            </el-button>
            <el-button v-if="+statusPremise === 2" type="primary" @click="updatePremiseStateFun(1, true)">
                开启楼盘和相关联点位
            </el-button>
            <el-button v-if="+statusPremise === 2" type="primary" @click="updatePremiseStateFun(1, false)">
                仅开启楼盘
            </el-button>
        </TipsDailog>
        <premises :build-source="houseData.source" :is-drawer-show="houseData.isDrawerShow" :type="houseData.handleType"
            :apply-order-id="houseData.applyOrderId" :premise-id="houseData.premiseId" :transfer-id="houseData.transferId"
            @onDrawerShow="onAddPremises" @createHouse="createHouse"></premises>
        <premises :is-drawer-show="houseData.isCreateDrawerShow" type="CREAT" @onDrawerShow="onCreatePremises"></premises>
        <CostEntry v-if="isCostEntryShow" v-model="isCostEntryShow" :premises-data="premisesData" is-edit="true">
        </CostEntry>
        <BuildingDrawer v-model:show="houseData.buildingDrawerShow" :default-data="houseData.buildingDrawerData"
            @onDataChange="onSearchList"></BuildingDrawer>
        <batch-import v-if="isBatchImportShow" v-model:isPointDrawerShow="isBatchImportShow" :type="importType"
            @refresh="onSearchList"></batch-import>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed, defineProps, watch, nextTick } from 'vue';
import { useStore } from 'vuex';
import { searchpremises, exportPremises, updatePremiseState, searchDraft, draftDelete } from '@/api/houseManage';
import { HousePages, IQueryHouse, AuditStatus } from './houseManageType';
import type { FormInstance } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination.vue';
import TipsDailog from '@/components/TipsDailog.vue';
import premises from './components/Premises.vue';
import CostEntry from './components/CostEntry.vue';
import HouseSearch from '@/components/HouseSearch.vue';
import BatchImport from './components/BatchImport.vue';
import BuildingDrawer from '@/views/resource/components/buildingDrawer/Index.vue';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/index.vue';
import { setTableMaxHeight, $btnAuth } from '@/utils/common';
import XcSwitch from '@x-tech/fe-pc-components/src/components/XcSwitch/index.vue';

const ruleFormRef = ref<FormInstance>();
const props = defineProps({
    auditStatus: {
        type: String,
        default: '',
    },
});

const columnsList = [
    {
        label: '楼盘名',
        key: 'name',
        prop: {
            width: '200px',
            fixed: 'left',
        },
    },
    {
        label: '区域',
        key: 'provinceName',
        prop: {
            minWidth: '240px',
        },
        render: true,
    },
    {
        label: '物业类型',
        key: 'typeName',
        prop: {
            minWidth: '150px',
        },
    },
    {
        label: '详细地址',
        key: 'address',
        prop: {
            minWidth: '260px',
        },
    },
    {
        label: '点位数',
        key: 'onSaleMediaNum',
        prop: {
            minWidth: '110px',
        },
        render: true,
    },
    {
        label: '禁忌行业',
        key: 'taboo',
        prop: {
            minWidth: '240px',
        },
        render: true,
    },
    {
        label: '操作',
        key: 'action',
        render: true,
        prop: { fixed: 'right', minWidth: '280' },
    },
];
const columns = ref(columnsList);
const store = useStore();
const applyOrderId = ref('');
const statusPremise = ref('');
const dialogBtnLoading = ref(false);
const maxTableHeight = ref(0);
const isBatchImportShow = ref(false);
const isCostEntryShow = ref(false);
const houseSearch = ref(null);
const importType = ref('');
const premisesData = ref({});
// 初始化的数据
const houseData = reactive(new HousePages());
const selectedData = reactive<IQueryHouse>(houseData.selectedData);
// 搜索相关的列表信息
const onSearchList = async (): Promise<void> => {
    houseData.loading = true;
    try {
        const data = await (props.auditStatus === AuditStatus.DRAFT
            ? searchDraft(selectedData)
            : searchpremises(selectedData));
        if (data.data) {
            houseData.houseList = data.data.map((item: any) => {
                return { ...item, premiseStatus: item.status === 1 };
            });
        } else {
            houseData.houseList = [];
        }
        console.log(houseData.houseList);

        selectedData.total = data.total;
        houseData.loading = false;
    } catch {
        houseData.loading = false;
    }
};

onMounted(async () => {
    await nextTick();
    maxTableHeight.value = setTableMaxHeight('xc-table');
    console.log(maxTableHeight.value);
    onSearchList();
});
const commonList: any = computed(() => store.state.app.common.CommonList);

const houseSearchAuditStatus: number[] | null = computed(() =>
    props.auditStatus === AuditStatus.DRAFT ? null : [props.auditStatus]
);

// 重置搜索表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return;
    }
    [selectedData.province, selectedData.city, selectedData.area] = [0, 0, 0];
    formEl.resetFields();
    onSearchList();
};

const onBatchImport = async (type: string): Promise<void> => {
    console.log(type);
    importType.value = type;
    isBatchImportShow.value = true;
};
// 分页的页码改变
const changePage = (page: number) => {
    selectedData.pageNo = page;
    onSearchList();
};
// 分页的条数
const changePageSize = (pageSize: number) => {
    selectedData.pageSize = pageSize;
    onSearchList();
};
// 改变楼盘审核通过的状态弹框确认
const updatePremiseStateCheck = (row: any): void => {
    houseData.title = +statusPremise.value === 1 ? '是否关闭楼盘？' : '是否开启楼盘？';
    houseData.content =
        +statusPremise.value === 1
            ? '关闭楼盘后，将下架该楼盘关联的所有点位'
            : '开启楼盘后，将开启该楼盘关联的所有点位';
    houseData.dialogVisible = true;
    console.log(houseData.title);
};
// 点击新建楼盘按钮的操作
const onAddDrawerShow = (): void => {
    houseData.applyOrderId = '';
    houseData.premiseId = '';
    houseData.handleType = 'ADD';
    houseData.isDrawerShow = true;
};
// 点击新建楼盘弹框确认操作
const onAddPremises = (type: string): void => {
    type && onSearchList();
    houseData.isDrawerShow = false;
};
// 点击创建楼盘弹框确认操作
const onCreatePremises = (type: string): void => {
    type && onSearchList();
    houseData.isCreateDrawerShow = false;
};

// 改变搜索区域
const onChangeArea = (area: number[]): void => {
    [selectedData.province, selectedData.city, selectedData.area] = area || [];
    onSearchList();
};
// 到处通过楼盘审核的楼盘数据
const onExportPremises = async (): Promise<void> => {
    dialogBtnLoading.value = true;
    houseData.loading = true;
    try {
        const data = await exportPremises({ auditStatus: [3] });
        dialogBtnLoading.value = false;
        houseData.loading = false;
        window.open(data);
    } catch {
        dialogBtnLoading.value = false;
        houseData.loading = false;
    }
};

// 点击搜索楼盘操作里面的创建建楼盘
const createHouse = (): void => {
    houseData.isDrawerShow = false;
    houseData.isCreateDrawerShow = true;
};
// 查询搜索的楼盘
const changeProjectName = (value: any): void => {
    selectedData.premiseName = value.name;
    onSearchList();
};
// 编辑和查看楼盘
const onCheck = (scope: any, type: string): void => {
    if (props.auditStatus === AuditStatus.DRAFT) {
        houseData.transferId = scope.row.transferId;
        houseData.applyOrderId = null;
        houseData.premiseId = null;
    } else {
        houseData.applyOrderId = scope.row.applyOrderId;
        houseData.premiseId = scope.row.premiseId;
    }

    houseData.source = scope.row.source;
    houseData.handleType = type;
    houseData.isDrawerShow = true;
};
// 开关楼盘图
const switchBuildingDrawer = (rowData: any): void => {
    houseData.buildingDrawerShow = !houseData.buildingDrawerShow;
    if (houseData.buildingDrawerShow) {
        houseData.buildingDrawerData = {
            areaArr: [rowData.row.province, rowData.row.city, rowData.row.area],
            buildingId: rowData.row.premiseId,
            buildingName: rowData.row.name,
        };
    }
};
// 更新楼盘操作
const updatePremiseStateFun = async (status: any, type: any): Promise<void> => {
    const data = {
        applyOrderId: applyOrderId.value,
        premisesId: houseData.premiseId,
        status: status,
        enablePoint: type,
    };
    await updatePremiseState(data);
    onSearchList();
    houseData.dialogVisible = false;
};
// 操作楼盘状态的切换操作
const beforeChange = (row: any): Promise<void> => {
    statusPremise.value = row.status;
    applyOrderId.value = row.applyOrderId;
    houseData.premiseId = row.premiseId;
    updatePremiseStateCheck(row);
    return Promise.reject();
};
const onMediaNum = (row: any): string => {
    const onSaleMediaNum = row.onSaleMediaNum ? `正常：${row.onSaleMediaNum}<br/>` : '';
    const maintainMediaNum = row.maintainMediaNum ? `维修：${row.maintainMediaNum}<br/>` : '';
    const takeDownMediaNum = row.takeDownMediaNum ? `下架：${row.takeDownMediaNum}` : '';
    const text = `${onSaleMediaNum}${maintainMediaNum}${takeDownMediaNum}`;
    return text;
};
const hanleOnSign = (scope: any) => {
    isCostEntryShow.value = true;
    premisesData.value = scope.row;
};
const hanleOnDelete = async ({ row }): void => {
    await ElMessageBox.confirm('是否删除楼盘，点击确认后楼盘将从草稿箱删除');
    await draftDelete(row.transferId);
    onSearchList();
};

// 楼盘的状态切换的改变，数据改变
watch(
    () => props.auditStatus,
    (auditStatus) => {
        resetForm(ruleFormRef.value);
        houseData.transferId = null;
        houseData.applyOrderId = null;
        houseData.premiseId = null;
        houseSearch.value.projectNameList = [];
        houseData.selectedData.auditStatus = auditStatus;
        selectedData.pageNo = 1;
        selectedData.pageSize = 10;
        columns.value = columnsList;
        if (+auditStatus === 3) {
            columns.value = columnsList;
        } else {
            columns.value = columnsList.filter((item) => item.key !== 'onSaleMediaNum' && item.key !== 'status');
        }
        onSearchList();
    }
);
</script>

<style lang="scss" scoped>
:deep(.el-table__body) {
    .xc-table-column {
        // background-color: pink;
        height: 52px !important;

        ._cell {
            padding-top: 0;
            padding-bottom: 0;
        }
    }
}

.tableCalss {
    margin-top: 30px;
}

.auditFormClass {
    :deep(.el-input__inner) {
        width: 280px;
    }
}

.switch {
    :deep(.el-switch__inner) {
        // width: 50px;
        // left: 40%;
        // text-align: left;
    }

    :deep(.el-switch__core) {
        // width: 48px;
    }
}
</style>
